<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <van-address-edit :area-list="areaList" show-delete show-set-default
        :area-columns-placeholder="['请选择', '请选择', '请选择']" :address-info="address" @save="save" @delete="del" />
</template>

<script setup>
//引入地区数据
import { areaList } from '@vant/area-data'

// eslint-disable-next-line no-undef
const { proxy } = getCurrentInstance();

// 获取收获地址的编辑id
let id = proxy.$route.query.id ?? 0
// eslint-disable-next-line no-undef
let address = ref({})
let business = proxy.$business.value

// eslint-disable-next-line no-undef
onBeforeMount(() => {
    info()
})

// 查询收获地址方法
const info = async () => {
    // 发生请求
    var result = await proxy.$POST({
        url: "address/info",
        params: {
            busid: business.id,
            id,
        }
    })

    if (result.code == 0) {
        proxy.$fail({
            message: result.msg,
            duration: 1000,
            onClose: () => {
                // 跳转，返回上一个界面
                proxy.$router.go(-1)
            }
        })
        return false
    }

    var data = result.data

    // 修改地址的默认信息
    address.value = {
        name: data.consignee,
        tel: data.mobile,
        addressDetail: data.address,
        areaCode: data.district || data.city || data.province,
        isDefault: data.status == "1" ? true : false
    }
}

// 更新
const save = async (values) => {
    // 组装数据
    var params = {
        id,
        busid: business.id,
        consignee: values.name,
        address: values.addressDetail,
        mobile: values.tel,
        status: values.isDefault ? "1" : "0",
        code: values.areaCode
    }

    // 发生请求
    var result = await proxy.$POST({
        url: "address/edit",
        params
    })

    if (result.code == 0) {
        proxy.$fail(result.msg)
        return false
    } else {
        proxy.$success({
            message: result.msg,
            duration: 1000,
            onClose: () => {
                // 跳转，返回上一个界面
                proxy.$router.go(-1)
            }
        })
    }
}

// 删除
// eslint-disable-next-line no-unused-vars
const del = async (item) => {
    proxy.$confirm({
        title: '删除提醒',
        message: '是否确认删除该收获地址'
    }).then(async () => {
        var result = await proxy.$POST({
            url: "address/del",
            params: {
                busid: business.id,
                id,
            }
        })

        if (result.code == 0) {
            proxy.$fail(result.msg)
            return false
        }

        // 返回上一个界面
        proxy.$success({
            message: result.msg,
            duration: 1000,
            onClose: () => proxy.$router.go(-1)
        })
    }).catch(() => { })
}

</script>